<?php

namespace app\web\controller;

use app\model\Mch;

class Login extends Base
{

    /**
     * Undocumented 登录页面
     *
     * @return void
     */
    public function index(){
        
        $admin_auth = Session("auth_mch");
        if($admin_auth){
           return $this->redirect('/web/home');
        }
        return view("home/login");
    }
    /**
     * Undocumented 登录处理
     *
     * @return void
     */
    public function dologin(){
        $user_name = $this->request->param("user_name",'','strip_tags,trim');
        $password = $this->request->param("password",'','strip_tags,trim');
        $google_code = $this->request->param("google_code",'','strip_tags,trim');
        if(empty($user_name) || empty($password) || empty($google_code)){
            return $this->error("缺少必填参数");
        }
        $info = Mch::where("mch",$user_name)->find();//查询商户信息
        if(!$info){
            return $this->error('商户不存在');
        }
        $Aes = new \Aes();
        $pwd = $Aes->decrypt($info->password);//解密
        if($password != $pwd){
            return $this->error('密码不正确');
        }
        if($info->googl_secret){
            if(!Googl_validation($info->googl_secret,$google_code)){
                
                return $this->error("谷歌验证码错误");
            }
        }
        $info->secret_key = md5key(6);
        $info->save();
        Session('auth_mch',['mch_id'=>$info->id,'mch'=>$info->mch,'secret_key'=>$info->secret_key,'is_agent'=>$info->is_agent,'md5key'=>$info->md5key]);
        get_one_insert("mch",$info->mch,$info);
        getMchLog($info->mch,'登录商户后台',$info->is_agent);
        return $this->success('登录成功','/web/home');
    }
    /**
     * Undocumented tuichu 退出登录
     *
     * @return void
     */
    public function logout(){

        Session("auth_mch",null);
        
        return $this->error('退出成功','/web/login');
    }
    /**
     * Undocumented 绑定谷歌
     *
     * @return void
     */
    public function google(){
        $auth_mch = Session('auth_mch');
        $info = Mch::where("id",$auth_mch['mch_id'])->find();
        if($info){
            $info->googl_secret = $this->request->param('google_secret');
            $info->save();
            get_one_insert("mch",$info->mch,$info);
            getMchLog($auth_mch['mch_id'],'绑定谷歌',$auth_mch['is_agent']);
            return $this->success('绑定成功');
        }
    }
}